﻿using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile.Samples.Location;

namespace SimpleGPSApp.Controls
{
    public partial class SatellitesSignal : UserControl
    {
        Font mainFont = new Font(FontFamily.GenericSansSerif, 8.25f, FontStyle.Regular);
        Brush greenBrush = new SolidBrush(Color.Green);
        Brush redBrush = new SolidBrush(Color.Red);
        Brush blackBrush = new SolidBrush(Color.Black);
        Brush activeBrush = null;
        Pen greenPen = new Pen(Color.Green);
        Pen blackPen = new Pen(Color.Black);
        private Bitmap buffer;
        private GpsPosition position = null;

        public GpsPosition Position
        {
            set
            {
                position = value;
                if (position != null)
                {
                    this.Refresh();
                }
            }
        }

        public SatellitesSignal()
        {
            InitializeComponent();
            this.buffer = new Bitmap(this.Width, this.Height);
        }

        private void DrawSignalStrength(Graphics g)
        {
            if (position != null)
            {
                Satellite[] satArray = position.GetSatellitesInView();
                int y = (int)(0.1f * Height);
                int signalBarWidth = (Width - (int)Math.Ceiling(0.2f * Width)) / satArray.Length;
                int signalBarHeight = Height - (int)Math.Ceiling(0.3f * Height);
                int margin = (int)Math.Ceiling(0.1f * signalBarWidth);

                for (int i = 0; i < satArray.Length; i++)
                {
                    int x = (signalBarWidth + margin) * i + margin;

                    g.DrawRectangle(blackPen, new Rectangle(x, y, signalBarWidth, signalBarHeight));

                    activeBrush = position.SatelliteIsInSolution(satArray[i]) ? greenBrush : redBrush;
                    int signal = satArray[i].SignalStrength % signalBarHeight;
                    g.FillRectangle(activeBrush, new Rectangle(x + 1, y + signalBarHeight - signal, signalBarWidth - 1, signal));
                    g.DrawString(satArray[i].Id.ToString(), mainFont, blackBrush, x, y + signalBarHeight + 3);
                }
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            this.buffer = new Bitmap(this.Width, this.Height);

            using (Graphics graphics = Graphics.FromImage(this.buffer))
            {
                graphics.Clear(this.BackColor);
                DrawSignalStrength(graphics);
            }

            e.Graphics.DrawImage(buffer, 0, 0);
            base.OnPaint(e);
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
        }
    }
}
